import { getToken, relogin } from '@/utils/util.js'
import qs from 'qs'

let time = null; // 保存请求时的定时器,做一个节流操作,避免多次触发弹窗
/**
 * 通用请求方法
 * @param ns this对象
 * @param api 请求地址
 * @param params 所带参数
 * @param method 请求方法
 * @param headers 请求头
 * @return {Promise<unknown>} Promise对象
 */
export function request(ns, api, params = {}, method = "GET", headers = {}, isFormData = false, interapi = '',responseType = "") {
	return new Promise(function (resolve, reject) {
		let isQt = /^\/loginapi\//.test(api)
		// 服务市场换成qt的token
		let arr = [
			'commerce/agency/querySettledAgency',
			'serviceRequirement/list',
			'commerce/agency/queryAgencyDetail',
			'ecomm/category/queryList',
			'commerce/agency/settled',
			'commerce/agency/querySettledProcess',
			'commerce/agency/checkHasSettled',
			'serviceRequirement/detail',
		]
		let interShow = arr.indexOf(interapi)
		let qttoken = localStorage.getItem("qtToken")
		// console.log('interShow', interShow,qttoken)
		if (interShow > -1 || isQt) {
			headers['X-Base-Token'] = qttoken
		}

		method = method.toUpperCase()
		let token = getToken()
		let m = api.match(/captchaImage/)
		if (token != null && token != undefined && token != '' && !m && interShow == -1) {
			headers['Authorization'] = token
		}
		if (method == 'POST' && isFormData) {
			headers['Content-Type'] = 'application/x-www-form-urlencoded'
			params = qs.stringify(params)
		}
		ns.axios.request({
			url: api,
			params: method == 'GET' ? params : {},
			data: method != 'GET' ? params : {},
			headers: headers,
			method: method,
			responseType: responseType
		}).then(result => {
      let res = result.data
			if (res.code == 401) {
				if(time) return;
				ns.$message.error("您需要登录才能访问当前页面，请先登录")
				time = setTimeout(()=>{
						relogin(ns)
						time = null;
					},500)
				return;
			}else if(res.code == 402){
				setTimeout(()=>{
					relogin(ns)
				},500)
				return;
			}
			resolve(res);
		}).catch(err => {
      let { message } = err
      if(message == "Network Error") {
        message = "后端接口连接异常"
      } else if(message.includes("timeout")) {
        message = "系统接口请求超时"
      } else if(message.includes("Request failed with status code")) {
        message = "系统异常，请稍后重试!"
      }
      ns.$message.error(message)
			reject(err)
		});
	});
}

/**
 * 上传文件的请求
 * @param url
 * @returns {AxiosPromise}
 */
export function uploadFile(ns, url, data) {
	let headers = {
		'access-user': window.localStorage.getItem('access-user'),
		'Content-Type': 'multipart/form-data'
	}
	let token = getToken()
	if (token != null && token != undefined && token != '') {
		headers.Authorization = token
	}
	let config = {
		//请求的接口，在请求的时候，如axios.get(url,config);这里的url会覆盖掉config中的url
		url: url,
		transformResponse: [function (data1) {
			var data = data1;
			if (typeof data1 == "string") {
				data = JSON.parse(data1);
			}
			return data;
		}],
		//请求头信息
		headers: headers,

		//跨域请求时是否需要使用凭证
		//withCredentials: true,
		// 返回数据类型
		responseType: 'json', //default
	};
	return new Promise(function (resolve, reject) {
		ns.axios.post(url, data, config).then(result => {
      let res = result.data
			if (res.code == 401) {
				relogin(ns)
				return
			}
			resolve(res);
		}).catch(err => {
			reject(err);
		});
	})
}
